package com.changgou.seckill.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.seckill.feign.SeckillOrderFeign;
import com.changgou.util.CookieUtil;
import com.changgou.util.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author wz
 * @company 公司
 * @create 2020-04-17 15:43
 */
@RestController
@RequestMapping("/seckillgoods")
public class SeckillOrderController {

    @Autowired
    private SeckillOrderFeign seckillOrderFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/add")
    public Result add(@RequestParam("time") String time, @RequestParam("id") Long id,String random) {
        String cookieValue = this.readCookie();
        String  redisRandomCode = (String) redisTemplate.opsForValue().get("randomcode_" + cookieValue);

        if (StringUtils.isEmpty(redisRandomCode)){
            return new Result(false, StatusCode.ERROR,"下单失败");
        }
        if (!random.equals(redisRandomCode)){
            return new Result(false,StatusCode.ERROR,"下单失败");
        }
        Result result = seckillOrderFeign.add(time, id);
        return result;
    }

    /**
     * 接口加密
     * 生成随机数存入redis，10秒有效期
     */
    @GetMapping("/getToken")
    @ResponseBody
    public String getToken() {
        String randomString = RandomUtil.getRandomString();
        String cookieValue = this.readCookie();
        redisTemplate.opsForValue().set("randomcode_"+cookieValue, randomString, 5,TimeUnit.SECONDS);
        return randomString;
    }

    //读取cookie
    private String readCookie() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String uid = CookieUtil.readCookie(request, "uid").get("uid");
        return uid;
    }

}